package com.foo.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.foo.servicesCall.NewsWSClient;
import com.foo.servicesCall.NewsStub.News;
import com.foo.servicesCall.NewsStub.NewsArray;


/**
 * Servlet implementation class NewsServlet
 */
public class NewsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		RequestDispatcher dispatcher;
		HttpSession session = request.getSession(true);
		NewsArray newsArray = null;
		
		session.setAttribute("NewsData", null);
		NewsWSClient client = new NewsWSClient();
		
		String sortBased = request.getParameter("SortBased");
		
		if(sortBased.equalsIgnoreCase("allnews"))
		{
			newsArray = client.getAllNews();
		}
		else if(sortBased.equalsIgnoreCase("newsbykeyword"))
		{
			String Keyword = request.getParameter("newsbykeyword");
			newsArray = client.getNewsByKeyword(Keyword);
		}
		else if(sortBased.equalsIgnoreCase("newsbycategory"))
		{
			String Category = request.getParameter("newsbycategory");
			newsArray = client.getNewsByCategroy(Category);
		}
		
		News[] news =null;
		if(newsArray!=null)
			{
			news = newsArray.getNews();
			}
		
		if(sortBased.equalsIgnoreCase("newsbycategory"))
		{
			String Category = request.getParameter("newsbycategory");
			for(int i=0;i<news.length;i++)
			{
				news[i].setNews_category(Category);
			}
		}
		
		session.setAttribute("NewsData", news);
		dispatcher = getServletContext().getRequestDispatcher("/news.jsp");
		dispatcher.forward(request, response);	      
	}

}
